<?php

namespace Togetwzb\Yii2\Aliyun\Sts;

use AlibabaCloud\SDK\Sts\V20150401\Models\AssumeRoleRequest;
use AlibabaCloud\SDK\Sts\V20150401\Models\AssumeRoleResponseBody;
use AlibabaCloud\SDK\Sts\V20150401\Sts;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
use Exception;

/**
 * Sts 相关
 * 基于sts SDK 升级版本的
 *
 * ``` 加载一下插件
 * "yiisoft/yii2": "~2.0",
 * "alibabacloud/sts-20150401": "*"
 * ```
 */
class StsHelper
{
    /**
     * 阿里云sts生成临时账号
     *
     * ```
     * $baseConfig = [
     *      'accessKeyId' => '',
     *      'accessKeySecret' => '',
     *      //'endpoint' => '',
     * ];
     * $assumeRoleConfig = [
     *      'roleArn' => '',
     *      'roleSessionName' => '',
     *      'policy' => '{
     *          "Version": "1",
     *          "Statement": [
     *          {
     *              "Effect": "Allow",
     *              "Action": [
     *                  "oss:PutObject",
     *                  "oss:GetObject"
     *               ],
     *              "Resource": "acs:oss:*:*:xxxxxx/*"
     *               }
     *          ]
     *      }'
     * ]
     * ```
     * @param array $baseConfig 基础配置
     * @param array $assumeRoleConfig 角色相关配置
     * @param array $runtimeOptions 运行环境配置
     * @param bool $reset 是否重置
     * @return AssumeRoleResponseBody
     * @throws Exception
     * @see Config
     * @see AssumeRoleRequest
     */
    public static function assumeRoleUser($baseConfig = [], $assumeRoleConfig = [], $runtimeOptions = [], $reset = false, $cacheOption = ['duration' => 3000, 'key' => 'StsOssRoleSessionName'])
    {
        $config = new Config($baseConfig);
        $client = new Sts($config);

        $cache = \Yii::$app->cache;

        $key = $cacheOption['key'];
        $duration = $cacheOption['duration'];

        if ($reset === true || ($assumeRoleResponseBody = $cache->get($key)) === false) {
            $assumeRoleRequest = new AssumeRoleRequest($assumeRoleConfig);
            $runtime = new RuntimeOptions($runtimeOptions);
            //            try {
            // 复制代码运行请自行打印 API 的返回值
            $rs = $client->assumeRoleWithOptions($assumeRoleRequest, $runtime);
            $assumeRoleResponseBody = $rs->body;
            $cache->set($key, $assumeRoleResponseBody, $duration);
            //            } catch (Exception $error) {
            ////                throw new \yii\base\Exception($error->getMessage(), $error->getCode(), $error);
            //            }
        }
        /** @var AssumeRoleResponseBody $assumeRoleResponseBody */
        return $assumeRoleResponseBody;
    }
}